<?php
namespace app\wx\controller;

use wxpay\JsApiPay;
use wxpay\WxPayConfig;
use wxpay\WxPayApi;
use wxpay\WxPayUnifiedOrder;
use wxpay\WxPayNotifyResults;
use app\common\model\WxpayOrder;
use wxpay\WxPayOrderQuery;
use wxpay\WxPayException;
//import('qrcode', EXTEND_PATH);

class Wxx
{
    private $APPID = 'wx5c6558a180573edf';


    public function index()
    {
        return '<style type="text/css">*{ padding: 0; margin: 0; } div{ padding: 4px 48px;} a{color:#2E5CD5;cursor: pointer;text-decoration: none} a:hover{text-decoration:underline; } body{ background: #fff; font-family: "Century Gothic","Microsoft yahei"; color: #333;font-size:18px;} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.6em; font-size: 42px }</style><div style="padding: 24px 48px;"> <h1>:) </h1><p> ThinkPHP V5.1<br/><span style="font-size:30px">12载初心不改（2006-2018） - 你值得信赖的PHP框架</span></p></div><script type="text/javascript" src="https://tajs.qq.com/stats?sId=64890268" charset="UTF-8"></script><script type="text/javascript" src="https://e.topthink.com/Public/static/client.js"></script><think id="eab4b9f840753f8e7"></think>';
    }

    public function viewjsapi()
    {
        return view("/viewjsapi");
    }

    /**
     * 授权
     * @return mixed
     */
    public function getCode()
    {
        if (isset($_GET['code'])) {
            return $_GET['code'];
        }
        $tools = new JsApiPay();
        $tools->GetOpenid();
    }

    /**
     * 获取openid
     */
    public function getOpenid()
    {
        $params = request()->param();

        if (!$params['code']) {
            ajaxReturn(2);
        }
        $tools = new JsApiPay();
        $openId = $tools->getOpenidFromMp($params['code']);
        ajaxReturn(0,['openid'=>$openId]);
    }

    /**
     * 添加订单
     */
    public function postAddOrder()
    {

        $params=[
            'total_fee'=>1,
            'openid'=>'oPcHts09eGE37JdN2eEo9Dy76kL0',
            'tyt_id'=>1,
        ];
        try{
            $tools = new JsApiPay();

            $Out_trade_no = mt_rand(100,999).date("YmdHis").mt_rand(100,999);
            //②、统一下单1
            $input = new WxPayUnifiedOrder();
            $input->SetBody("桃园公寓商品详情");
            $input->SetAttach("附加数据");
            $input->SetOut_trade_no($Out_trade_no);
            $input->SetTotal_fee($params['total_fee']);
            $input->SetTime_start(date("YmdHis"));
            $input->SetTime_expire(date("YmdHis", time() + 600));
            $input->SetGoods_tag("订单优惠标记");
            $input->SetMch_id("1558864601");
            $input->SetAppid("wx5c6558a180573edf");
            $input->SetNotify_url("http://wx.taoyuanapartment.com/jsapiNotify");
            $input->SetTrade_type("JSAPI");
            $input->SetOpenid($params['openid']);
            $config = new WxPayConfig();
            dump($input);
            $order = WxPayApi::unifiedOrder($config, $input);
            dump($order);
            if($order['return_code']!='SUCCESS' || $order['return_msg']!='OK'){
                ajaxReturn(20001,$order['return_msg']);
            }

            //echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
            $jsApiParameters = $tools->GetJsApiParameters($order);
            dump($jsApiParameters);
//            WxpayOrder::create([
//                'two_prepay_id'         => $order['prepay_id'],
//                //'two_order_detail'      => json_encode($order),
//                //'two_order_payment'     => $jsApiParameters,
//                'two_order_outtradeno'  => $Out_trade_no,
//                'tyt_id'                => $params['tyt_id'],
//                'two_order_payprice'    => $params['total_fee'],
//            ]);
//            //获取共享收货地址js函数参数
//            //$editAddress = $tools->GetEditAddressParameters();

            ajaxReturn(0,$jsApiParameters);

        } catch(\Exception $e) {
            ajaxReturn(20001,$e->getMessage());
        }
    }

    /**
     * jsapi回调
     */
    public function jsapiNotify()
    {
        $config = new WxPayConfig();

        //获取通知的数据
        $xml = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : file_get_contents("php://input");

        if (empty($xml)) {
            # 如果没有数据，直接返回失败
            return false;
        }

        //xml转数组
        try {
            $objData = \wxpay\WxPayNotifyResults::Init($config, $xml);
        } catch (\Exception $e) {
            $msg = $e->getMessage();
            myLog("jsapiNotify",'回调-数据转换xml失败<br/>'.$msg);
            return false;
        }

        $data = $objData->GetValues();

        //TODO 1、进行参数校验
        if(!array_key_exists("return_code", $data)
            || (array_key_exists("return_code", $data) && $data['return_code'] != "SUCCESS")) {
            //TODO失败,不是支付成功的通知
            //如果有需要可以做失败时候的一些清理处理，并且做一些监控
            myLog("jsapiNotify",'回调-进行参数校验异常异常<br/>');
            return false;
        }
        if(!array_key_exists("transaction_id", $data)){
            myLog("jsapiNotify_".$data["transaction_id"],'回调-输入参数不正确<br/>');
            return false;
        }

        //订单回调接收数据 入库
        WxpayOrder::where('two_order_outtradeno',$data['out_trade_no'])
            ->update([
                'two_order_notifydata'      => json_encode($data),
                'two_order_transactionid'   => $data["transaction_id"],
                'two_order_paytime'         => time()
            ]);

        //TODO 2、进行签名验证
        try {
            $checkResult = $objData->CheckSign($config);
            if($checkResult == false){
                myLog("jsapiNotify_".$data["transaction_id"],'回调-签名错误<br/>');
                return false;
            }
        } catch(\Exception $e) {
            myLog("jsapiNotify_".$data["transaction_id"],'回调-签名错误<br/>'.$e->getMessage());
        }

        //TODO 3、处理业务逻辑
        myLog("jsapiNotify_".$data["transaction_id"],"回调数据：".json_encode($data)."<br/>");
        try {
            $Queryorder_arr = $this->Queryorder($data["transaction_id"]);
        } catch (\Exception $e) {
            myLog("jsapiNotify_".$data["transaction_id"],'回调-订单查询数据:'.$e->getMessage()."<br/>");
            return false;
        }
        //查询订单，判断订单真实性
        if(!$Queryorder_arr){
            myLog("jsapiNotify_".$data["transaction_id"],'回调-订单查询失败<br/>');
            return false;
        }
        $return_xml = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        return $return_xml;
    }

    /**
     * @param $transaction_id
     * @return bool|\wxpay\成功时返回，其他抛异常
     * @throws WxPayException
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function Queryorder($transaction_id)
    {
        $input = new WxPayOrderQuery();
        $input->SetTransaction_id($transaction_id);

        $config = new WxPayConfig();
        $result = WxPayApi::orderQuery($config, $input);

        //订单回调接收数据 入库
        WxpayOrder::where('two_order_transactionid',$transaction_id)
            ->update([
                'two_order_queryresult'         => json_encode($result),
                'two_order_tradestate'          => $result["trade_state"]
            ]);

        myLog("jsapiNotify_".$transaction_id,"回调-订单查询数据:".json_encode($result));
        if(array_key_exists("return_code", $result)
            && array_key_exists("result_code", $result)
            && $result["return_code"] == "SUCCESS"
            && $result["result_code"] == "SUCCESS")
        {
            return $result;
        }
        return false;
    }

    /**
     * 前端查询订单状态
     */
    public function webOrderQuery()
    {

        $params = request()->param();

        if (!$params['transaction_id']) {
            ajaxReturn(2);
        }
        $orderdetail = $this->Queryorder($params['transaction_id']);
        myLog('orderdetail',json_encode($orderdetail));
        //查询订单表数据是否一致
        $localorderdetail = WxpayOrder::where('two_order_transactionid',$params['transaction_id'])->find();

        //查询状态和
        if ($orderdetail['trade_state']!=$localorderdetail['two_order_tradestate']) {
            ajaxReturn(20002);
        }

        ajaxReturn(0,['trade_state'=>$orderdetail['trade_state']]);

    }

    /**
     * 订单充值状态修改
     */
    public function postWebRechangeUpdate()
    {
        $params = request()->param();

        $validate = validate('OrderValidate');
        if (!$validate->scene('webRechangeUpdate')->check($params)) {
            ajaxReturn(1, $validate->getError());
        }

        $data = [
            'two_prepay_id' => $params['prepay_id'],
            'tyt_id'        => $params['tyt_id']
        ];

        $diff = array_diff($params,$data);//验证多余的参数

        if ($diff) {
            ajaxReturn(20003,$diff);
        }
        $result = WxpayOrder::where($data)->where('two_isrecharge',1)->find();

        if (!$result) {
            ajaxReturn(20004);
        }

        $row = WxpayOrder::where($data)->update(['two_isrecharge'=>2]);

        if (!$row) {
            ajaxReturn(20005);
        }
        ajaxReturn(0);
    }
}
